package com.stoneframe.base.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.DatagramChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;

import java.net.InetSocketAddress;

import com.stoneframe.base.util.Logger;

public class ServerUDPChannelFactory {
	
	private static final Logger logger=Logger.getLogger(ServerUDPChannelFactory.class);
	
	protected static Channel createAcceptorChannel(final ChannelType channelType,
			final InetSocketAddress localAddress,final ServerUDPHandler serverHandler){
		final Bootstrap serverBootstrap=ServerUDPBootstrapFactory.createServerBootstrap(channelType);
		serverBootstrap.option(ChannelOption.SO_REUSEADDR, false)
			.handler(new ChannelInitializer<DatagramChannel>(){

				@Override
				protected void initChannel(DatagramChannel ch)
						throws Exception {
					// TODO Auto-generated method stub
					final ChannelPipeline pipeline=ch.pipeline();
					pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60));//这是读写超时炒作，实际上在UDP上没有多少的意义
                    pipeline.addLast("handler", serverHandler);
				}
				
			});
		logger.info("创建UDP。。。。。。。。+++++++++++++++++++");
		try{
			ChannelFuture channelFuture=serverBootstrap.bind(
					new InetSocketAddress(localAddress.getPort())).sync();
			channelFuture.awaitUninterruptibly();
			if(channelFuture.isSuccess()){
				return channelFuture.channel();
			}else{
				logger.warn(String.format("Failed to open socket! Cannot bind to port: %d!",
                        localAddress.getPort()));
			}
		}catch(InterruptedException e){
			logger.error("Failed to create acceptor socket.", e);
		}
		return null;
		
	}

}
